import 'package:flutter/material.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/utils/log_util.dart';
import 'package:xws/utils/storage_util.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/utils/tools_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/app_img.dart';

/// 视频装载按钮
class VideoBox extends StatefulWidget {
  const VideoBox({
    Key? key,
    required this.path,
    this.width,
    this.height,
    this.maxWidth = 100,
    this.maxHeight = 100,
    this.quality = 50,
    this.imageFit = BoxFit.contain,
  }) : super(key: key);

  @override
  _VideoBoxState createState() => _VideoBoxState();

  final double? width;
  final double? height;

  final int maxWidth;
  final int maxHeight;
  final int quality;

  final String path;

  final BoxFit imageFit;
}

class _VideoBoxState extends State<VideoBox> with SafeState<VideoBox> {
  String? _thumbnail;

  @override
  void initState() {
    super.initState();
    _init();
  }

  /// 准备封面数据
  Future<void> _init() async {
    if (widget.path.isNotEmpty) {
      try {
        final String? fileName = await VideoThumbnail.thumbnailFile(
          video: widget.path,
          thumbnailPath: await getLocalPath('videoThumbnail'),
          imageFormat: ImageFormat.JPEG,
          maxWidth: widget.maxHeight,
          maxHeight: widget.maxHeight,
          quality: widget.quality,
        );

        if (fileName != null) {
          safeSetState(() => _thumbnail = fileName);
        }
      } catch (e) {
        error('封面生成失败:$e');
      }
    }
  }

  /// 预览内容
  Future<void> _preView() async {
    await assetsViewer(context, <String>[widget.path], isVideo: true);
  }

  @override
  Widget build(BuildContext context) {
    return AppBtn.noPadding(
      onTap: _preView,
      width: widget.width,
      height: widget.height,
      radius: 4,
      color: black(context),
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          if (_thumbnail != null)
            AppImg.fitCover(
              url: _thumbnail,
              fit: widget.imageFit,
              width: widget.width,
              height: widget.height,
              radius: 4,
            ),
          Icon(
            Icons.play_circle_fill_rounded,
            size: 40,
            color: white(context),
          ),
        ],
      ),
    );
  }
}
